package com.xiaoman.read.file;

import com.xiaoman.read.config.Chapter;
import com.xiaoman.read.config.Config;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.MediaType;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.SpineReference;
import nl.siegmann.epublib.epub.EpubReader;
import nl.siegmann.epublib.service.MediatypeService;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class EpubFile implements File {
    @Override
    public void read(String url) {
        Config.setFileType("epub");
        try {
            java.io.File file = new java.io.File(url);
            EpubReader epubReader = new EpubReader();
            Book book = epubReader.readEpub(new FileInputStream(file));
            Config.chapters = extractChapters(book);
            Config.images = extractImages(book);
            Config.setCurrentChapterIndex(0);
            displayCurrentChapter();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private List<Chapter> extractChapters(Book book) {
        List<Chapter> chapters = new ArrayList<>();
        try {
            // 提取脊柱信息
            List<SpineReference> spineReferences = book.getSpine().getSpineReferences();
            for (SpineReference spineReference : spineReferences) {
                try (InputStream inputStream = spineReference.getResource().getInputStream()) {
                    String xml = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
                    Chapter chapter = new Chapter(xml);
                    chapters.add(chapter);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return chapters;
    }
    private Map<String, BufferedImage> extractImages(Book book) {
        Map<String, BufferedImage> images = new HashMap<>();
        for (Resource resource : book.getResources().getAll()) {
            MediaType mediaType = resource.getMediaType();
            if (mediaType.equals(MediatypeService.JPG)
                    || mediaType.equals(MediatypeService.PNG)
                    || mediaType.equals(MediatypeService.GIF)) { // 检查是否为图片类型
                try (InputStream inputStream = resource.getInputStream()) {
                    BufferedImage image = ImageIO.read(inputStream);
                    if (image != null) {
                        images.put(resource.getHref(), image);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return images;
    }

    @Override
    public void displayCurrentChapter() {
        int currentIndex = Config.getCurrentChapterIndex();
        if (currentIndex >= 0) {
            if (Config.getFileType().equalsIgnoreCase("epub") && currentIndex < Config.chapters.size()) {
                Chapter chapter = Config.chapters.get(currentIndex);
                StringBuilder contentBuilder = new StringBuilder();
                contentBuilder.append("### ").append(chapter.title).append("\n\n");
                contentBuilder.append(chapter.content).append("\n\n");
                // 设置内容
                Config.readUI.getTextContent().setText(contentBuilder.toString());
                // 显示图片
                displayImagesForChapter(chapter);
            }
        }
    }

    private void displayImagesForChapter(Chapter chapter) {
        // 假设章节内容中包含图片的引用，例如 <img src="image.jpg" />
        String content = chapter.content;
        Document doc = Jsoup.parse(content);
        Elements imgElements = doc.select("img");

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        // 添加文本
        JTextPane textPane = new JTextPane();
        textPane.setEditable(false);
        textPane.setText("### " + chapter.title + "\n\n" + chapter.content + "\n\n");
        panel.add(textPane);

        // 添加图像
        for (Element imgElement : imgElements) {
            String src = imgElement.attr("src");
            BufferedImage image = Config.images.get(src);
            if (image != null) {
                ImageIcon icon = new ImageIcon(image);
                JLabel label = new JLabel(icon);
                panel.add(label);
            }
        }

        // 设置内容
        Config.readUI.getTextContent().setText(""); // 清空原有内容
        Config.readUI.getScrollPane().getViewport().setView(panel); // 设置新的视图
    }

}
